package com.ea.admin.utils;


import com.ea.admin.service.AuthService;
import com.ea.common.auth.NowUser;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class NowUserGetter {
    @Resource
    AuthService authService;

    // 获得当前的用户
    public NowUser getNowUser() {
        return authService.getNowUserByUsername(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
    }

    public String getUsername() {
        return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
    }

    public String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull
                (RequestContextHolder.getRequestAttributes())).getRequest();
        return request.getHeader("Authorization");
    }
}
